﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Travel.MVC
{
    /// <summary>
    /// EnumHelper
    /// </summary>
    public class EnumHelper
    {
        /// <summary>
        /// Enums to select list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selectedItem">The selected item.</param>
        /// <param name="descDict">The desc dict.</param>
        /// <returns></returns>
        public static SelectList EnumToSelectList<T>(T selectedItem, Dictionary<T, string> descDict)
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("必须为枚举类型");
            }

            var enumValues = Enum.GetValues(typeof(T)).Cast<T>().Select(e => new KeyValuePair<int, string>(Convert.ToInt32
            (e),
            descDict.ContainsKey(e) ? descDict[e] : e.ToString()
            ));

            return new SelectList(enumValues, "Key", "Value", Convert.ToInt32(selectedItem));
        }

        /// <summary>
        /// Enums to select list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="descDict">The desc dict.</param>
        /// <returns></returns>
        public static SelectList EnumToSelectList<T>(Dictionary<T, string> descDict)
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("必须为枚举类型");
            }

            var enumValues = Enum.GetValues(typeof(T)).Cast<T>().Select(e => new KeyValuePair<int, string>(Convert.ToInt32
            (e),
            descDict.ContainsKey(e) ? descDict[e] : e.ToString()
            ));

            return new SelectList(enumValues, "Key", "Value");
        }
    }
}